<%@page import="java.awt.geom.Area"%>
<%@page import="org.springframework.security.core.context.SecurityContextHolder"%>
<%@page import="org.apache.commons.lang.StringUtils"%>
<%@page import="org.apache.commons.lang.time.DateFormatUtils"%>
<%@page import="org.springframework.util.CollectionUtils"%>
<%@page import="java.util.Collection"%>
<%@ include file="../common/common_include.jsp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	AreaMapForm form = (AreaMapForm)request.getAttribute("command");
	TbAppAuditingAreas areaMap = null;
	if(null!=request.getAttribute("areaMap")){
		areaMap = (TbAppAuditingAreas)request.getAttribute("areaMap");
	}
	String points = null!=areaMap.getPoints()?areaMap.getPoints():"";
	UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	List<TbAppAreas> areaMapList=null;
	if(null!=request.getAttribute("areaMapList")){
		areaMapList = (List<TbAppAreas>)request.getAttribute("areaMapList");
	}
	String coordinate = (String)request.getAttribute("coordinate");
	String cityName=(String)request.getAttribute("city");
	String[] areaArr=new String[areaMapList.size()];
	for(int i=0;i<areaMapList.size();i++){
		areaArr[i]=areaMapList.get(i).getPoints();
	}
%>

<div>
	<form id="AreaMapForm" target="_coreIframe" method="post" action="" enctype="multipart/form-data">
		<div class="breadcrumb">
			<div class="bcIcon"></div>
			<ul class="bcNav">
				<li>编辑围栏地图</li>
			</ul>
		</div>
		<table class="formTable">
			
			<tr>
				<td class="tdTitle">围栏名称：</td>
				<td>
					<input class="inputText xs" type="text"  value="<%=(null!=areaMap.getAreaname())?areaMap.getAreaname():""%>" name="areaname"  readonly="readonly">
					<span class="errorTipWrap" id="errorTip_areaname"></span>
				</td>
			</tr>
			<tr>
				<td class="tdTitle">站点ID：</td>
				<td>
					<input class="inputText xs" type="text"  value="<%=StringUtils.isNotBlank(areaMap.getSiteid())?areaMap.getSiteid():""%>" name="siteid" readonly="readonly">
					<span class="errorTipWrap" id="errorTip_siteid"></span>
				</td>
			</tr>
			<input type="hidden" value="<%=cityName%>" name="" id="cityName">
			<input type="hidden" value="<%=StringUtils.isNotBlank(areaMap.getCity())?areaMap.getCity():""%>" name="city">
			<input type="hidden" value="<%=StringUtils.isNotBlank(areaMap.getProvince())?areaMap.getProvince():""%>" name="province">
			<input type="hidden" name="checkuser" value="<%=StringUtils.isNotBlank(user.getUsername())?user.getUsername():""%>">
			<input type="hidden" name="areaid" value="<%=StringUtils.isNotBlank(areaMap.getAreaid())?areaMap.getAreaid():""%>">
			<input type="hidden" name="judge" value="core">
			<input id="points" type="hidden" name="points" value="">
			<tr>
				<td class="tdTitle">备注：</td>
				<td>
					<textarea class="textArea"  name="remark"><%=StringUtils.isNotBlank(areaMap.getRemark())? areaMap.getRemark():"" %></textarea>
				</td>
			</tr>
			<tr>
				<td  class="tdTitle">区域地图：</td>
				<td>
					<div id="allmap" style="overflow:hidden;zoom:1;position:relative;">     
			            <div id="map" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;">加载地图中......</div>  
			        </div>  
			        <!-- <div id="result">  
			            <input type="button" value="清除区域地图" onclick="clearAll()"/>  
			            <input type="button"  value="重新加载原区域地图" onclick="showPolygon()" /> 			            			            
			        </div> 	 -->		        
				</td>
			</tr>
			<tr>
				<td class="tdTitle"></td>
				<td>
					<div>
						<a class="a-btn-microsoft" href="javascript:XF.Area.auditingAreaMap()"><span>检查完毕退出</span></a>
					</div>
				</td>
			</tr>	
		</table>
	</form>
	<iframe id="_coreIframe" name="_coreIframe" style="display: none;"></iframe>
</div>
<style type="text/css">
	body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";}
	#allmap {width: 800px; height:600px; overflow: hidden;}
	#result {width:100%;font-size:12px;}
	dl,dt,dd,ul,li{
		margin:0;
		padding:0;
		list-style:none;
	}
	p{font-size:12px;}
	dt{
		font-size:14px;
		font-family:"微软雅黑";
		font-weight:bold;
		border-bottom:1px dotted #000;
		padding:5px 0 5px 5px;
		margin:5px 0;
	}
	dd{
		padding:5px 0 0 5px;
	}
	li{
		line-height:28px;
	}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=BhnIKXHC4luCst3qvbTGrPOD"></script>
<!--加载鼠标绘制工具-->
<script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
<link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
<!--加载检索信息窗口-->
<script type="text/javascript" src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>
<link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css" />
<script type="text/javascript">
	var coordinate = <%=coordinate%>;
	var defaultPoint=[{"lat":"22.93043","lng":"113.3991"}];
    var points;
	<%if(points!=null||!points.equals("")){%>
    	points= <%=points%>;
    <%}else{%>
    	points= defaultPoint;
	<%}%>
	var polygonArr = [];
	for (var i = 0; i < points.length; i++) {
		polygonArr.push(new BMap.Point(points[i].lng,points[i].lat));
	}
    var areaArr = [];
    <%for(int i=0;i<areaArr.length;i++){%>
    areaArr[<%=i%>]=<%=areaArr[i]%>;
    <%}%>
    // 百度地图API功能 
    var map = new BMap.Map('map');
    var poi = new BMap.Point(points[0].lng,points[0].lat);
    map.centerAndZoom(poi, 10);    
	var top_left_navigation = new BMap.NavigationControl({offset: new BMap.Size(5, 5)});  //左上角，添加默认缩放平移控件	       
	map.addControl(top_left_navigation);
	map.addControl(new BMap.MapTypeControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT})); //卫星、三维地图切换
    map.enableScrollWheelZoom();    
    var overlays = [];  
    var overlaycomplete = function(e){  
        overlays.push(e.overlay);   
    };  
    var styleOptions = {  
        strokeColor:"red",    //边线颜色。  
        fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。  
        strokeWeight: 3,       //边线的宽度，以像素为单位。  
        strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。  
        fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。  
        strokeStyle: 'solid' //边线的样式，solid或dashed。  
    }
    //实例化鼠标绘制工具  
    var drawingManager = new BMapLib.DrawingManager(map, {  
        isOpen: false, //是否开启绘制模式  
        enableDrawingTool: true, //是否显示工具栏 
        drawingMode:BMAP_DRAWING_POLYGON,//绘制模式  多边形
        drawingToolOptions: {  
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置  
            offset: new BMap.Size(6, 10), //偏离值  
            drawingModes:[
                          BMAP_DRAWING_POLYGON
                      ]
        },  
        polygonOptions: styleOptions, //多边形的样式  
    });    
    function FullScreenControl(){
		this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
		this.defaultOffset = new BMap.Size(140, 10);
	}
	FullScreenControl.prototype = new BMap.Control();
	FullScreenControl.prototype.initialize = function(map){
		var fullLock = false;
		var $fullMap = $('#allMap');
		var div = document.createElement("a");
		div.appendChild(document.createTextNode("全屏"));
		div.id = "btnFullScreen";
		$(".layout-panel-center").css("z-index","4");
		div.style.cssText = 'display:inline-block;height:47px;line-height:47px;background-color:#fff;width:64px;text-align:center;color:#000;font-size:12px;border: 1px solid #666;    border-radius: 5px;overflow:hidden;cursor:pointer;';
		div.onclick = function(e){
			if (!fullLock && !document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
				fullLock = true;
				document.getElementById("btnFullScreen").innerHTML = '退出全屏';
				document.getElementById('map').style.cssText = 'position:fixed; left:0px; top:0px; bottom:0px; right:0px;height:100%;z-index:1003';
				if (document.documentElement.requestFullscreen) {
					document.documentElement.requestFullscreen();
				} else if (document.documentElement.mozRequestFullScreen) {
					document.documentElement.mozRequestFullScreen();
				} else if (document.documentElement.webkitRequestFullscreen) {
					document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
				}
				$(".header").hide();
			} else {
				fullLock = false;
				document.getElementById("btnFullScreen").innerHTML = '全屏';
				document.getElementById('map').style.cssText = 'position:relative;height:600px';
				if (document.cancelFullScreen) {
					document.cancelFullScreen();
				} else if (document.mozCancelFullScreen) {
					document.mozCancelFullScreen();
				} else if (document.webkitCancelFullScreen) {
					document.webkitCancelFullScreen();
				}
				$(".header").show();
			}
		}
		map.getContainer().appendChild(div);
		return div;
	}
	map.addControl(new FullScreenControl());   
     //添加鼠标绘制工具监听事件，用于获取绘制结果  
    drawingManager.addEventListener('overlaycomplete', overlaycomplete);  
     
   
    function draw(type){
    	if(overlays.length == 0){
    		drawingManager.open();   
            drawingManager.setDrawingMode(type);
    	}else{
    		alert("区域地图已存在，如果要重新选定区域先清除原有区域，再新建区域")
    	}
          
    }     
          
    function clearAll() {  
        for(var i = 0; i < overlays.length; i++){  
            map.removeOverlay(overlays[i]);  
        }        
        overlays.length = 0
        $("#points").val("");
    }  
    function getPoint(){
    	if(overlays.length >0){
    		_points = "[";
            var _split = "";            
    		for(var i = 0; i < overlays.length; i++){  
                var overlay=overlays[i].getPath();
                for (var j = 0; j < overlay.length; j++) {
                	_points += _split + '{"lng":"' + overlay[j].lng + '","lat":"' + overlay[j].lat + '"}';
                	_split = ","
				}
    		}
    		_points += "]";
    		$("#points").val(_points);
    	}else{
    		$("#points").val("");
    	}
    }  
    function Editing(state){  
        for(var i = 0; i < overlays.length; i++){  
            state=='enable'?overlays[i].enableEditing():overlays[i].disableEditing();  
        }  
    }
    function  showPolygon(){
    	clearAll()
      var polygon = new BMap.Polygon(polygonArr, styleOptions);  //创建多边形  
      map.addOverlay(polygon);   //增加多边形  
      overlays.push(polygon); //是否把该图像加入到编辑和删除行列 
      getPoint()
     }
	 // 编写自定义函数,创建标注
	function addMarker(point,label){
		var label = new BMap.Label(label,{offset:new BMap.Size(20,-10)})
		var marker = new BMap.Marker(point);
		map.addOverlay(marker);
		marker.setLabel(label);
	}
    function getBoundary(city){
        var bdary = new BMap.Boundary();
        bdary.get(city, function(rs){       //获取行政区域
            //map.clearOverlays();        //清除地图覆盖物
            var count = rs.boundaries.length; //行政区域的点有多少个
            if (count === 0) {
                alert('未能获取当前市区区域');
                return ;
            }
            var pointArray = [];
            for (var i = 0; i < count; i++) {
                var ply = new BMap.Polygon(rs.boundaries[i],
                    {strokeWeight: 2, strokeColor: "black",fillColor:"",fillOpacity: 0.1}); //建立多边形覆盖物
                map.addOverlay(ply);  //添加覆盖物
                pointArray = pointArray.concat(ply.getPath());
            }
            map.setViewport(pointArray);    //调整视野
        });
    }
    $(document).ready(showPolygon());
    $(document).ready(getBoundary($("#cityName").val()));
    $(document).ready(function(){
        for (var i=0;i<areaArr.length;i++){
        	var getRandomColor = '#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).substr(-6);
    		var polygonArr2=[];
    		p=areaArr[i];
    		if (p==undefined||p==''){
    			continue;
    		}
    		for (var j = 0; j < p.length; j++) {
        		polygonArr2.push(new BMap.Point(p[j].lng,p[j].lat));
        	}
    		var s2 = {       //已划分区域边界样式
		            strokeColor:getRandomColor,    //边线颜色。  
		            fillColor:getRandomColor,      //填充颜色。当参数为空时，圆形将没有填充效果。  
		            strokeWeight: 2,       //边线的宽度，以像素为单位。  
		            strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
		            fillOpacity: 0.4,      //填充的透明度，取值范围0 - 1。  
		            strokeStyle: 'solid' //边线的样式，solid或dashed。
		    	}
    		var polygon2 = new BMap.Polygon(polygonArr2, s2);
    		map.addOverlay(polygon2);
        }
        if(coordinate.length>0 && coordinate!=null){
	    	for (var i = 0; i < coordinate.length; i++) {
	    		var point = new BMap.Point(coordinate[i].lng, coordinate[i].lat);
	    		addMarker(point,coordinate[i].pointname)
			}
    	}
    });
</script>



